const PENDING = 'pending'; // 等待 状态
const FULFILLED = 'fulfilled'; // 成功 状态
const REJECTED = 'rejected'; // 失败 状态

class myPromise {
  constructor(executor) {
    executor(this.resolve.bind(this), this.reject.bind(this));
  }
  // 当前的状态
  state = PENDING;
  // 结果值
  result = undefined;

  resolve(val) {
    // 状态不是 pending 就直接返回
    if (this.state !== PENDING) return;
    // 修改状态为成功状态
    this.state = FULFILLED;
    // 绑定成功结果
    this.result = val;
  }

  reject(val) {
    // 状态不是 pending 就直接返回
    if (this.state !== PENDING) return;
    // 修改状态为失败状态
    this.state = REJECTED;
    // 绑定失败结果
    this.result = val;
  }

  then(successCb, failCb) {
    if (this.state === FULFILLED) {
      successCb(this.result);
    } else if (this.state === REJECTED) {
      failCb(this.result);
    }
  }
}
